import sys, time, hashlib, base64, requests
from jinja2 import Environment, FileSystemLoader
from selenium import webdriver
from collections import defaultdict


# python fastqStat4gz.py /home/zhengzhiqiang/0528.S200040707.csv /home/zhengzhiqiang/S200040707/fastq/SequenceStat.txt /home/zhengzhiqiang/S200040707/fastq/S200040707


def html_set_data(texdata, outprefix):
    '''
    texdata:待填入tempQC.html中的数据
    outprefix:第四个参数（/home/zhengzhiqiang/S200040707/fastq/S200040707）
    '''
    # 路径拼接为绝对路径？
    path_dir = '/' + '/'.join(outprefix.split('/')[1:-1])
    # 相关环境
    env = Environment(loader=FileSystemLoader('/home/zhengzhiqiang/workflow/qcstat/'))
    # 数据填入模板 
    template = env.get_template('tempQC.html')
    buf = template.render(texdata)
    html = f'{outprefix}.fastq.Stats.html'
    # 生成fastq.Stats.html
    with open(html, "w", encoding="utf-8") as fp:
        fp.write(buf)
    # 浏览器相关选项
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--disable-dev-shm-usage')
    browser = webdriver.Chrome(options=chrome_options)
    # 打开浏览器3ms后退出？
    browser.get(f'file://{html}')
    time.sleep(3)
    browser.quit()

    # try:
    #     url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c635edcf-1adb-4277-9152-060d661c20b7'
    #     name = outprefix.split('/')[-1]
    #     requests.post(url, json={"msgtype": "text", "text": {"content": f"{name}"}})
    #     with open('fastq.stats.png', 'rb') as fq:
    #         png = fq.read()
    #         md5 = hashlib.md5(png).hexdigest()
    #         b64 = base64.b64encode(png).decode('utf-8')
    #         data = {'msgtype': 'image','image': {'base64': b64,'md5': md5}}
    #         requests.post(url, json=data)
    # except Exception as e:
    #     print(e)
    #     sys.exit('PNG is not exists!')


# 根据simplesheet和Sequence.txt生成fastq.Stats.xls
'''
simpleSheet格式
Chemistry,Default,,,,,,
,,,,,,,
[Reads],,,,,,,
75,,,,,,,
,,,,,,,
[Settings],,,,,,,
Adapter,CTGTCTCTTATACACATCT,,,,,,
,,,,,,,
[Data],,,,,,,
Sample_ID,Sample_Name,Sample_Plate,Sample_Well,*I7_Index_ID,*index,Sample_Project,Description
S216YM0360,,,,81,L1,,
S216YM0361,,,,82,L1,,
S216YM0362,,,,83,L1,,
S216YM0363,,,,84,L1,,
S216YM0364,,,,85,L1,,
S216YM0365,,,,86,L1,,

Sequence.txt格式
        #Sequence        Barcode             Count         Percentage(%)
        TCACGATACA       Barcode103        48897390        6.927668
        ACGGTAATGG       Barcode101        45592658        6.459460
        ...
'''
with open(sys.argv[1]) as csv, open(sys.argv[2]) as stat, open(sys.argv[3]+'.fastq.Stats.xls', 'w') as out:
#    need_sample=[]
    flag = 0
    sample = {}
    # 处理simplesheet
    for i in csv:
        if flag == 0:
            if i.startswith('Sample_ID'):
                flag = 1
            else:
                continue
            continue
        # 从表头开始
        if flag == 1:
            x = i.split(',')
#            if x[0].find('BY')>-1:
#                need_sample.append(f'Barcode{x[4]}')
#                continue
            # sample:{Barcode:sampleID}
            sample[f'Barcode{x[4]}'] = x[0]
    # Sequence.txt 跳过表头
    stat.readline()
    outdata = {'tabledata1': []}
    outdata['tabledata1'].append({'sampleID': 'sampleID', 'tindex': 'index', 'treadsNumber': 'readsNumber'})

    out.write('sampleID\tindex\treadsNumber\n')
    for i in stat:
        x = i.strip().split('\t')
 #       if x[0] in need_sample:continue 
        if x[0].find('otherindex') > -1:
            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
            if int(x[1]) > 15_000_000:
                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'OIflag': True})
            else:
                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'OIflag': False})
        elif x[0].find('undecoded') > -1:
            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
            if int(x[1]) > 75_000_000:
                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'UDflag': True})
            else:
                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'UDflag': False})
        elif x[0] == 'TotalReads':
            out.write(f'{x[0]}\t{x[0]}\t{int(x[1]):,}\n')
            if int(x[1]) < 600_000_000:
                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'TTflag': True})
            else:
                outdata['tabledata1'].append({'sampleID': f'{x[0]}', 'tindex': f'{x[0]}', 'treadsNumber': f'{int(x[1]):,}', 'TTflag': False})
        elif sample[x[0]].startswith('NC'):
            out.write(f'{sample[x[0]]}\t{x[0]}\t{int(x[1]):,}\n')
            if int(x[1]) > 5_000_000:
                outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'NCflag': True})
            else:
                outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'NCflag': False})
        else:
            if int(x[1]) > 15000000 or sample[x[0]].find('-YF') > -1 or sample[x[0]].find('-KY') > -1 or sample[x[0]].find('-SY') > -1:
                bit15M = False
            else:
                bit15M = True
            out.write(f'{sample[x[0]]}\t{x[0]}\t{int(x[1]):,}\n')
            outdata['tabledata1'].append({'sampleID': sample[x[0]], 'tindex': x[0], 'treadsNumber': f'{int(x[1]):,}', 'bit15M': bit15M})

    html_set_data(outdata, sys.argv[3])
